package com.learn.demo1;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.binding.BinderAwareChannelResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.client.RestTemplate;

/**
 * Created by 郑靖 on 2017/9/18.
 */
@Configuration
@EnableBinding
public class MessageHelper {

    @Bean
    @ConditionalOnMissingBean(RestTemplate.class)
    public  RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Autowired
    BinderAwareChannelResolver resolver;

    @Autowired
    RestTemplate restTemplate;


    protected  static final long DEFAULT_TIME_OUT = 5000;
    public static final String HEAD_NAME_UUID = "uuid";
    public static final String HEAD_NAME_RECEIPT = "receipt";
    /**
     * 发送消息 （当主题或队列无效是会抛出IllegalArgumentException）
     * @param destinationName 主题或者队列名称
     * @param message 消息体
     * @return 是否发送成功
     */
    public <T> boolean sendMessage(String destinationName, T message) {

//        Boolean result = restTemplate.getForObject("http://basic-service/message?destinationName=" + destinationName, Boolean.class);
        Boolean result = true;
        System.err.println("check successful");
        if(!result) {
            throw new IllegalArgumentException("invalid destinationName:"+ destinationName);
        }

        Message<?> body = MessageBuilder.withPayload(message)
                .setHeader(HEAD_NAME_UUID, java.util.UUID.randomUUID().toString())
                .setHeader(HEAD_NAME_RECEIPT,1==2)//TODO  是否需要回执
                .build();


        return resolver.resolveDestination(destinationName).send(body,DEFAULT_TIME_OUT);

    }

    @Autowired
    RabbitTemplate rabbitTemplate;

    public <T> boolean sendTrMessage(String destinationName,T body){

        rabbitTemplate.convertAndSend( "simple", "simple-demo",
                message -> {
                    System.err.println("message:");
                    System.err.println(message);
                     return null;
                });
        return true;
    }



}
